package register

import (
	"center-data-platform/app/notice/notice"
	"center-data-platform/app/user/api/internal/svc"
	"center-data-platform/app/user/api/internal/types"
	"center-data-platform/app/user/api/model"
	"center-data-platform/utils/helper"
	"context"
	"database/sql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserRegisterLogic) UserRegister(req *types.RegisterRequest) (resp *types.RegisterResponse, err error) {
	password := req.Password
	salt := helper.RandomString(20)
	newPassword, err := helper.HashStr(password + salt)
	if err != nil {
		return nil, err
	}
	data := model.User{
		UserName:    req.UserName,
		Email:       req.Email,
		Phone:       req.Phone,
		Password:    newPassword,
		Salt:        salt,
		Role:        0,
		Avatar:      sql.NullString{String: req.Avatar, Valid: true},
		Bio:         sql.NullString{String: req.Bio, Valid: true},
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
		DeletedTime: sql.NullTime{},
		Status:      1,
	}
	err = l.svcCtx.DB.Create(&data).Error
	//result, err := l.svcCtx.UserModel.Insert(l.ctx, &data)
	if err != nil {
		return nil, err
	}
	insertId := data.Id
	// 发送注册成功的系统消息
	_, err = l.svcCtx.NoticeRpc.Send(l.ctx, &notice.NoticeReq{
		UserId:  []int64{insertId},
		Content: "恭喜你，注册成功！",
	})
	if err != nil {
		return nil, err
	}
	return &types.RegisterResponse{
		Base: types.Base{Code: 200, Msg: "注册成功"},
	}, nil
}
